import tkinter as tk
from tkinter import ttk, messagebox
import json
import os
import threading
import time

from spider import Spider


class App:
    def __init__(self, root):
        self.root = root
        self.root.title("医师信息下载系统")
        self.root.geometry("600x500")

        self.username = None
        self.password = None

        # 配置文件路径
        self.CONFIG_FILE = os.path.join(os.path.expanduser("~"), ".app_config.json")

        # 创建界面组件
        self.create_auth_section()
        self.create_date_section()
        self.create_download_section()

        # 加载保存的账号信息
        self.load_credentials()
        self.create_log_section()  # 创建日志区域

    # ================== 账号信息存储模块 ==================
    def create_auth_section(self):
        """用户认证模块"""
        auth_frame = ttk.LabelFrame(self.root, text="账号信息存储")
        auth_frame.pack(pady=10, padx=20, fill="x")

        ttk.Label(auth_frame, text="用户名:").grid(row=0, column=0, padx=5, pady=5)
        self.entry_user = ttk.Entry(auth_frame)
        self.entry_user.grid(row=0, column=1, padx=5, pady=5, sticky="ew")

        ttk.Label(auth_frame, text="密码:").grid(row=1, column=0, padx=5, pady=5)
        self.entry_pass = ttk.Entry(auth_frame, show="*")
        self.entry_pass.grid(row=1, column=1, padx=5, pady=5, sticky="ew")

        btn_frame = ttk.Frame(auth_frame)
        btn_frame.grid(row=2, columnspan=2, pady=5)

        ttk.Button(btn_frame, text="保存", command=self.save_credentials).pack(side=tk.LEFT, padx=5)
        # ttk.Button(btn_frame, text="清除", command=self.clear_credentials).pack(side=tk.LEFT, padx=5)

        self.lbl_auth_status = ttk.Label(auth_frame, text="状态：未保存")
        self.lbl_auth_status.grid(row=3, columnspan=2)

    def save_credentials(self):
        """保存账号信息到文件"""
        username = self.entry_user.get()
        password = self.entry_pass.get()
        if not username or not password:
            messagebox.showwarning("错误", "用户名和密码不能为空")
            return

        try:
            self.username = username
            self.username = password
            with open(self.CONFIG_FILE, 'w') as f:
                json.dump({
                    "username": username,
                    "password": password
                }, f, indent=2)

            self.update_auth_status()
            messagebox.showinfo("成功", f"账号信息已保存至：\n{self.CONFIG_FILE}")
        except Exception as e:
            messagebox.showerror("错误", f"保存失败：{str(e)}")

    def clear_credentials(self):
        """清除存储的账号信息"""
        try:
            if os.path.exists(self.CONFIG_FILE):
                os.remove(self.CONFIG_FILE)
                self.entry_user.delete(0, tk.END)
                self.entry_pass.delete(0, tk.END)
                messagebox.showinfo("成功", "账号信息已清除")
        except Exception as e:
            messagebox.showerror("错误", f"清除失败：{str(e)}")
        finally:
            self.update_auth_status()

    def load_credentials(self):
        """加载存储的账号信息"""
        try:
            if os.path.exists(self.CONFIG_FILE):
                with open(self.CONFIG_FILE, 'r') as f:
                    data = json.load(f)
                    self.username = data.get("username", "")
                    self.password = data.get("password", "")
                    self.entry_user.insert(0, data.get("username", ""))
                    self.entry_pass.insert(0, data.get("password", ""))
        except Exception as e:
            messagebox.showerror("错误", f"加载账号信息失败：{str(e)}")

        self.update_auth_status()

    def update_auth_status(self):
        """更新账号信息状态显示"""
        if os.path.exists(self.CONFIG_FILE):
            self.lbl_auth_status.config(text="状态：已保存账号信息", foreground="green")
        else:
            self.lbl_auth_status.config(text="状态：未保存账号信息", foreground="red")

    # ================== 日期范围模块 ==================
    def create_date_section(self):
        """日期范围选择模块"""
        date_frame = ttk.LabelFrame(self.root, text="日期范围选择格式为：2020-01-31")
        date_frame.pack(pady=10, padx=20, fill="x")

        ttk.Label(date_frame, text="开始日期:").grid(row=0, column=0, padx=5, pady=5)
        self.start_date = ttk.Entry(date_frame)
        self.start_date.insert(0, "2025-03-01")
        self.start_date.grid(row=0, column=1, padx=5, pady=5, sticky="ew")

        ttk.Label(date_frame, text="结束日期:").grid(row=1, column=0, padx=5, pady=5)
        self.end_date = ttk.Entry(date_frame)
        self.end_date.grid(row=1, column=1, padx=5, pady=5, sticky="ew")
        self.end_date.insert(0, "2025-03-31")


        ttk.Button(date_frame, text="确认范围", command=self.validate_dates).grid(row=2, columnspan=2, pady=5)

    def validate_dates(self):
        """验证日期范围有效性"""
        start = self.start_date.get()
        end = self.end_date.get()

        if not start or not end:
            messagebox.showwarning("错误", "必须填写开始和结束日期")
            return

        try:
            # 这里可以添加实际的日期验证逻辑
            time.strptime(start, "%Y-%m-%d")
            time.strptime(end, "%Y-%m-%d")
            messagebox.showinfo("成功", "日期范围有效")
            self.log(f"日期范围为  {self.start_date.get()}  {self.end_date.get()}")

        except ValueError:
            messagebox.showerror("错误", "日期格式无效，请使用 YYYY-MM-DD 格式")

    # ================== 下载模块 ==================
    def create_download_section(self):
        """下载控制模块"""
        dl_frame = ttk.LabelFrame(self.root, text="数据下载")
        dl_frame.pack(pady=10, padx=20, fill="x", expand=True)

        self.progress = ttk.Progressbar(dl_frame, orient="horizontal", length=400)
        self.progress.pack(pady=5)

        ttk.Button(dl_frame, text="开始下载", command=self.start_download).pack(pady=5)

    def start_download(self):
        if not os.path.exists(self.CONFIG_FILE):
            messagebox.showwarning("错误", "请先保存账号信息")
            self.log("错误: 请先保存账号信息")
            return

        # 模拟要下载的文件列表
        self.files_to_download = [f"file_{i}" for i in range(10)]
        self.total_files = len(self.files_to_download)
        self.downloaded_files = 0
        self.progress["value"] = 0

        # 创建线程池
        self.threads = []
        sp = Spider(username=self.username, password=self.password)
        sp.login()
        infos = sp.find_list(self.start_date.get(), self.end_date.get())
        messagebox.showinfo("查询结果", f"共找到 {len(infos)}份pdf 关闭弹窗开始下载")
        self.total_files = len(infos)
        for arg in infos:
            thread = threading.Thread(target=self.download_file, args=(arg,sp))
            self.threads.append(thread)
            thread.start()

        self.log("开始下载任务")

    def download_file(self, arg, sp:Spider):

        sp.download(**arg)
        with threading.Lock():
            self.downloaded_files += 1
            progress_value = (self.downloaded_files / self.total_files) * 100
            self.progress["value"] = progress_value
            self.log(f"文件 {arg['name']} 下载完成，当前进度: {progress_value}%")

        # 检查是否所有文件都已下载完成
        if self.downloaded_files == self.total_files:
            self.log("下载完成")

    # ================== 日志模块 ==================
    def create_log_section(self):
        """创建日志显示区域"""
        log_frame = ttk.LabelFrame(self.root, text="日志信息")
        log_frame.pack(pady=10, padx=20, fill="both", expand=True)

        self.log_text = tk.Text(log_frame, height=10, width=50)
        self.log_text.pack(pady=5, padx=5, fill="both", expand=True)
        self.log_text.config(state=tk.DISABLED)

    def log(self, message):
        """记录日志到界面和控制台"""
        self.log_text.config(state=tk.NORMAL)
        self.log_text.insert(tk.END, f"{message}\n")
        self.log_text.see(tk.END)
        self.log_text.config(state=tk.DISABLED)



if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()
